#Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.
#
#This file is part of the Mnova scripting toolkit.
#
#Authorized users of Mnova Software may use this file freely, but this file is provided AS IS
#with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
#FOR A PARTICULAR PURPOSE.


from smtplib import SMTP
from smtplib import SMTP_SSL as SMTPSecure
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.utils import formatdate, COMMASPACE

import os
import sys

if len(sys.argv) < 13:
	sys.exit("Wrong number of parameters passed")

aServer = sys.argv[1]
aLogin = sys.argv[2]
aPassword = sys.argv[3]
aFrom = sys.argv[4]
aTo =  eval(sys.argv[5])
aSubject = sys.argv[6]
aText = sys.argv[7]
aFiles = eval(sys.argv[8])
aType = sys.argv[9]
aSecure = eval(sys.argv[10])
aPort = eval(sys.argv[11])
aAuthentication = eval(sys.argv[12])
aDebug = eval(sys.argv[13])

try:	
	msg = MIMEMultipart()
	msg['From'] = aFrom
	msg['To'] = COMMASPACE.join(aTo)
	msg['Date'] = formatdate(localtime=True)
	msg['Subject'] = aSubject
	if (aType == 'true'):
		msg.attach(MIMEText(aText, 'html'))
	else:
		msg.attach(MIMEText(aText, 'plain'))

	for file in aFiles:
		part = MIMEApplication(open(file,"rb").read())
		part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(file)))
		msg.attach(part)

	if aSecure:
		if aPort:
			smtp = SMTPSecure(aServer, aPort)
		else:
			smtp = SMTPSecure(aServer)
	else:
		if aPort:
			smtp = SMTP(aServer, aPort)
		else:
			smtp = SMTP(aServer)
	
	smtp.set_debuglevel(aDebug)

	smtp.ehlo()

	if smtp.has_extn('STARTTLS'):
		smtp.starttls()
		smtp.ehlo()
		

	if aAuthentication > 0:
		if aAuthentication < 2:
			smtp.esmtp_features["auth"] = "LOGIN PLAIN"
				
		smtp.login(aLogin, aPassword)
	
	smtp.sendmail(aFrom, aTo, msg.as_string())
	smtp.quit()
	smtp.close()

except Exception as e:
	sys.exit(e)




